package com.file.filedeal.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author caoqianhuan
 * @date 2022/10/8
 * @Description:
 */

public class FileUtil {

    private static ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newSingleThreadExecutor();
    private static Set<String> fileTypeSet =
            Stream.of("pdf", "doc", "xlsx", "img", "other")
                    .collect(Collectors.toCollection(HashSet::new));
    public static String getFileType(String fileName) {
        String[] fileNames = fileName.split("\\.");
        String type = fileNames[fileNames.length-1];
        if (fileTypeSet.contains(type)) {
            return type;
        }
        return "other";
    }

    public static void storeFile(MultipartFile file, String url) {
        threadPoolExecutor.execute(() -> {
            OutputStream outputStream = null;
            InputStream inputStream = null;
            try {
                byte[] bytes = new byte[1024];
                inputStream = file.getInputStream();
                //创建式 路径必须存在
                outputStream = new BufferedOutputStream(new FileOutputStream(url + file.getOriginalFilename()));
                while (inputStream.read(bytes) > 0) {
                    outputStream.write(bytes);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
